package com.Cfeng.XiaohuanChat.service.impl;

import com.Cfeng.XiaohuanChat.entity.ChatUser;
import com.Cfeng.XiaohuanChat.repository.ChatUserRepository;
import com.Cfeng.XiaohuanChat.service.ChatUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/8/6
 */

@Service
@RequiredArgsConstructor
public class ChatUserServiceImpl implements ChatUserService {

    private final ChatUserRepository chatUserRepository;

    @Override
    public ChatUser addOrUpdateUser(ChatUser chatUser) throws IllegalAccessException {
        //应该查询出原来的再save
        ChatUser oldUser = queryUser(chatUser.getUserName());
        //如果有则更新
        if(oldUser != null) {
            Field[] fields = oldUser.getClass().getDeclaredFields();
            for(Field field : fields) {
                field.setAccessible(true);
                if(Objects.isNull(field.get(chatUser))) {
                    //查询对象的属性赋值给空的
                    field.set(chatUser,field.get(oldUser));
                }
            }
        }
        return chatUserRepository.save(chatUser);
    }

    @Override
    public void removeUser(ChatUser chatUser) {
        chatUserRepository.delete(chatUser);
    }

    @Override
    public ChatUser queryUser(String username) {
        return chatUserRepository.findByUserName(username);
    }
}
